/*
 *  @author zhangqiang
 *  @data 2017/03/14
 *   年检资料及收件地址
 * */

import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Button, Toast, WhiteSpace} from 'antd-mobile';

import {getWeixinConfig,} from '../../actions/homeAction';
import Style from './index.scss'
import getDataService from '../../services/getData'

//加载依赖
import AlipayJSOperation from '../../utils/alipayJSOperation'
import typeOfBrowser from '../../utils/typeOfBrowser'
import PageBar from '../../components/common/pageBar'
import ReModal from '../../components/common/reModal'
import Service from '../../components/common/customerService'

import DocumentList from '../../components/sendTheAddress/documentList';
import SendCxytjMessage from '../../utils/sendCxytjMessage';
import BackMeanSure from '../../utils/backMeanSure';
import urlOperation from '../../utils/urlOperation';
import common from '../../utils/common';

class SendTheAddress extends Component {
    constructor(props) {
        super(props);

        this.state = {
            latestData: {
                name: '', location: '', phone: '',
            }, //用户： 最新的地址
            consigneeAddress: {
                receiveAddress: '',  //寄送地址
                receiveName: '', //寄送姓名
                receivePhone: '', //寄送电话
            },// 下游 ：公司地址
            confirmStatus: 0, //按钮的状态
            isClose: props.params.isClose ? 'shut' : '',// 用这个来判断返回是否全部退出
            requirements: [],//所需资料列表
            inspectionType: { //
                inspectionType: null,
                driveType: null
            },
            carNumber: '',
        }
        this.orderId = this.props.params.orderId;
        this.paramsType = this.props.params.type || 'oneLine';
        this.paramsBtn = this.props.params.btn || 'btn';
        this.backMeanSureInstance = new BackMeanSure(this.goHome.bind(this), 'sendTheAddress');
        //关闭微信
        // this.WeXinOperation();

    }

    //返回首页
    goHome(back, stay, toUrl) {
        if ((this.state.inspectionType.inspectionType == 1 && this.state.confirmStatus == 3) || (this.state.inspectionType.inspectionType == 2 && this.state.confirmStatus == 2)) {
            if (typeOfBrowser.getChannelOfBrowser() == 'app') {
                //app直接关闭当前webview回到年检提醒
                common.closeAppView();
            }
            //支付宝有兼容性问题，中间使用location.href跳转或者跳转到其他外链，都无法直接回退回首页，此处直接跳回首页
            else if(typeOfBrowser.getChannelOfBrowser()=='aliPay'){
                toUrl(()=>{
                    this.context.router.push('/');
                })
            }
            else {
                history.pushState({}, '', '');
                let backNumber = -1 * history.length + 1;
                history.go(backNumber);
            }
        }
        else {
            if (typeOfBrowser.getChannelOfBrowser() == 'app') {
                //app直接关闭当前webview回到年检提醒
                common.closeAppView();
            }
            else {
                back();
            }
        }
    }

    //跳转到订单详情页
    goToDetail(back, stay, toUrl) {
        if (this.state.confirmStatus == 2) {
            let orderDetailUrl = location.href.split('/#')[0].split('#')[0];
            if (orderDetailUrl.indexOf('?') > 0) {
                orderDetailUrl += '&OutTradeNo=' + this.orderId
            }
            else {
                orderDetailUrl += '?OutTradeNo=' + this.orderId
            }
            orderDetailUrl += '/#/orderDetails';
            toUrl(orderDetailUrl);
            /*toUrl(()=>{
             this.context.router.push('/questions');
             })*/
        }
        else {
            back();
        }
    }

    componentWillMount() {

    }

    //微信屏蔽分享功能
    WeXinOperation() {
        let userChannel = typeOfBrowser.getChannelOfBrowser();
        if (!localStorage.getItem('type')) {
            if (localStorage.getItem('urlClose')) {
                if (userChannel == 'weixin') {
                    //React.unmountComponentAtNode(document.getElementById('app'))//删除组件
                    //关闭微信
                    this.props.dispatch(getWeixinConfig({signUrl: location.href}, (result) => {
                        wx.config({
                            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                            appId: result.appId, // 必填，公众号的唯一标识
                            timestamp: result.timestamp, // 必填，生成签名的时间戳
                            nonceStr: result.nonceStr, // 必填，生成签名的随机串
                            signature: result.signature,// 必填，签名，见附录1
                            jsApiList: ['hideOptionMenu', 'closeWindow'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                        });
                        wx.ready(() => {
                            wx.closeWindow();
                        });
                    }))
                } else if (userChannel == 'qq') {
                    //
                }
            } else {
                localStorage.setItem('urlClose', 1)
            }
        } else {

        }
    }


    /*    //微信后退按钮直接关闭
     weixinBackOperation(){
     window.history.replaceState({closeView:'sendTheAddress'},"","");
     window.history.pushState({}, "", "");
     window.history.forward();
     setTimeout(function () {
     //监听物理返回按钮
     window.addEventListener("popstate", function(e) {
     if(e.state.closeView=='sendTheAddress'){
     wx.closeWindow();
     }
     })
     },300);
     }*/

    submitConfirmationPostalOwn = (urlbtnsData, ifGoOn, isOneLine) => {//提交确定 当前是否已经提交过：urlbtnsData
        if (urlbtnsData != 3 && isOneLine != 'oneLine') {
            SendCxytjMessage.sendMessage({eventId: 'H5_E_OnlineMaterialandAddresspage_ClickSubmit'});
            // 提交确认
            if (!ifGoOn) {
                let tips = this.paramsType != 'ems' ? '您的年检资料是否准备齐全<br/>且已寄送，资料不齐会导致年<br/>检办理不成功和没法退款哦！' : '您是否已备齐办理所需资料，如已备<br/>好确认后将由邮政人员上门收件办理';
                ReModal.alert(<div style={{margin: '-.5rem 0 0', width: '5rem'}}><p>提示</p><p
                    className='pt20 font-26 darkgray' style={{lineHeight: '.4rem'}}
                    dangerouslySetInnerHTML={{__html: tips}}/></div>, () => {
                    this.submitConfirmationPostalOwn(1, true, this.paramsType);
                    SendCxytjMessage.sendMessage({eventId: 'H5_E_OnlineMaterialandAddresspage_ClickComfirmSubmit'});
                });
                return false;
            }

            let postData = {
                orderId: this.orderId,
                userAddress: this.state.latestData.location,
                mailType: this.paramsType,
                name: this.state.latestData.name,
                phone: this.state.latestData.phone,
            };
            let userChannel = typeOfBrowser.getChannelOfBrowser();
            Toast.hide();
            Toast.loading("", 30, () => Toast.info("网络错误", 2));
            getDataService.doConfirm(postData).then(data => {
                Toast.hide();
                if (data.code == 1000) {
                    Toast.success('提交成功', 2);
                    localStorage.removeItem('addressList_action')

                    this.setState({
                        isClose: 'shut'
                    });
                    this.getDATA(true)

                    //setTimeout(window.location.replace(`/index.html#/orderDetails/?OutTradeNo=${this.props.params.orderId}`), 500)  ///跳回首页
                } else {
                    Toast.info(data.msg);
                }
            });
        } else {
            // 查看进程
            let baseUrl = window.location.href.replace(window.location.hash, '').split('?')[0].replace('/#/', '');
            //当有从订单列表过来的type标记时重新添加上去，方便之后判断
            if (urlOperation.getParameters()['type'] == 'orderList') {
                baseUrl = `${baseUrl}?OutTradeNo=${this.orderId}&type=orderList`;
            }
            else {
                baseUrl = `${baseUrl}?OutTradeNo=${this.orderId}`;
            }
            //兼容天猫渠道，带上特定用户信息
            if (urlOperation.getParameters()['user_from'] && urlOperation.getParameters()['sign']) {
                let user_id = urlOperation.getParameters()['user_id'],
                    user_from = urlOperation.getParameters()['user_from'],
                    sign = urlOperation.getParameters()['sign'];
                baseUrl = `${baseUrl}&user_id=${user_id}&user_from=${user_from}&sign=${sign}`;
            }
            //发送埋点
            SendCxytjMessage.sendMessage({eventId: this.state.inspectionType.inspectionType == 1 ? 'H5_E_OnlineSubmitedMaterialandAddresspage_CheckCheckorderdetail' : 'H5_E_SubmitedMaterialandAddresspage_Checkorderdetail'});
            window.location.href = `${baseUrl}/#/orderDetails`; // 页面跳转到订单详情页面
        }


        SendCxytjMessage.sendMessage({eventId: 'Insepection_ExemptionDataConfirm_Submit'});
    };

    getDATA = (isSub) => {
        let postData = {
            orderId: this.orderId,
        }
        //详情接口 拿到寄送地址和收件地址
        Toast.hide();
        Toast.loading("", 30, () => Toast.info("网络错误", 2));
        getDataService.orderView(postData).then(resultData => {
            /*
             mailType	string	是	邮寄方式；ems邮政上门取件；person自主寄送资料（订单扩展字段）
             inspectionType	string	是	年检类型：1，免检；2，过线检
             driveType	string	否	车检类型：1，代驾检测；2，自驾检测
             driveMsg	String	否	车检类型提示信息：根据车检类型不同显示
             */

            if (resultData.code == 1000) {
                let result = resultData.data
                //    alert('用户收件名：' + JSON.stringify(result.name)) 
                this.setState({
                    consigneeAddress: Object.assign(this.state.consigneeAddress, {
                        receiveAddress: result.receiveAddress || '',  //下游 ：寄送地址
                        receiveName: result.receiveName, //下游 ：寄送姓名
                        receivePhone: result.receivePhone || '', //下游 ：寄送电话
                    }),
                    confirmStatus: result.confirmStatus, //按钮的状态 1 未点击  2 说明点击过了，应该隐藏
                    latestData: Object.assign(this.state.latestData, { // 用户地址
                        name: result.name,
                        location: result.userAddress || '',
                        phone: result.phone,
                    }),
                    inspectionType: Object.assign(this.state.inspectionType, {
                        inspectionType: result.inspectionType,  //年检类型：1，免检；2，过线检
                        mailType: result.mailType || 'person', //邮寄方式；ems邮政上门取件；person自主寄送资料（订单扩展字段）
                        driveType: result.driveType || '1', //车检类型：1，代驾检测；2，自驾检测
                    }),
                    carNumber: result.carNumber,
                    requirements: result.requirements || [],
                });
                Toast.hide();

                // 如果是点击事件，第一次点击提交事件后返回，才弹窗
                isSub && ReModal.showComponent(<div className='text-center' style={{margin: '-.2rem 0 0'}}><img
                    src="./images/select-check.png"/><p className='ptb20'>提交成功</p><Button className={Style.fixedBtn}
                                                                                          size='large'
                                                                                          onClick={() => this.submitConfirmationPostalOwn(3, true, this.paramsType)}
                                                                                          style={{
                                                                                              width: '100%',
                                                                                              margin: '0.2rem 0 0'
                                                                                          }}>查看订单详情</Button></div>);

            }
            else {
                Toast.info(resultData.msg, 2)
            }
            //发送埋点
            setTimeout(() => {
                //发送进入页面埋点事件
                this.sendInitMessage();
            }, 0);
        })
    };

    //发送进入页面埋点事件
    sendInitMessage() {
        let eventId = '';
        if (this.state.inspectionType.inspectionType == 1) {
            if (this.state.confirmStatus == 3) {
                eventId = 'H5_P_Interspection_EnterOnlineMaterialandAddresspage_submited';
            }
            else {
                eventId = 'H5_P_Interspection_EnterOnlineMaterialandAddresspage';
            }
        }
        else {
            eventId = 'H5_P_Interspection_EnterMaterialandAddresspage';
        }
        SendCxytjMessage.sendMessage({eventId: eventId});
    }

    componentDidMount() {
        this.backMeanSureInstance.bindBackMeansure();
        AlipayJSOperation.setRightButtonStatus(false);
        //设置标题
        AlipayJSOperation.setTitle('年检资料及收件地址');
        //设置标题颜色
        AlipayJSOperation.setBarColor('#2FB3FE');
        document.querySelector("title").innerHTML = "年检资料及收件地址";

        this.getDATA();

    }

    componentDidUpdate() {
    }

    componentWillUnmount() {
        AlipayJSOperation.removeLeftButtonEvent();
    }

    render() {
        let latestAdd = this.state.latestData

        return (
            <div className={Style.container}>
                <PageBar title="年检资料及收件地址" back={() => {
                    history.back()
                }}/>
                <div style={{
                    background: '#fff',
                    position: 'fixed',
                    bottom: '0',
                    zIndex: '-1',
                    width: '100%',
                    height: '100%'
                }}></div>

                {/** 1 顶部寄件方式 */}
                {this.state.inspectionType.inspectionType == 1 &&
                <div className='color111 font-26 border-bottom'
                     style={{margin: '0 .3rem', padding: '.6rem 1px .3rem 2px'}}>
                    <span>免检资料寄送方式：</span>
                    {this.state.inspectionType.mailType == 'ems' ? <span className={Style.icon11 + ' fr'}>邮政上门</span> :
                        <span className={Style.icon12 + ' fr'}>自主寄送</span>}
                </div>
                }
                {this.state.inspectionType.inspectionType == 2 &&
                <div className='color111 font-26 border-bottom'
                     style={{margin: '0 .3rem', padding: '.6rem 0 .3rem 2px'}}>
                    <span>上线检车检方式：</span>
                    {this.state.inspectionType.driveType == 1 ? <span className={Style.icon21 + ' fr'}>代驾检测</span> :
                        <span className={Style.icon22 + ' fr'}>自驾检测</span>}
                </div>
                }
                {/** 1 顶部寄件方式:end */}


                <div className={Style.sendTheAddress}>

                    {/**2 年检资料 */}
                    <div className={Style.box}>
                        <p className={Style.title_t}>
                            {this.state.inspectionType.inspectionType?(this.state.inspectionType.inspectionType == 1 ?
                                this.state.inspectionType.mailType == 'ems' ? '请准备好以下办理资料并确认后等待邮政快递员上门收件：' : '请尽快整理以下年检所需资料并寄送至车行易客服：'
                                :
                                this.state.inspectionType.driveType == 1 ? '请准备好待检测车辆和以下年检所需资料：' : '检测前请准备好下年检所需资料：'):''
                            }
                        </p>
                        <DocumentList requirements={this.state.requirements}/>
                    </div>
                    {/**2 年检资料 */}


                    {/**3 下游地址 ：只有免检里面的自主寄件，才有下游地址 */}
                    {this.state.inspectionType.inspectionType == 1 && this.state.inspectionType.mailType == 'person' &&
                    <div className={Style.box_address}>
                        <div className={Style.title_t}>资料寄送地址：</div>
                        <div className={Style.box_address_phone}>
                            <dl className={Style.address}>
                                <dt className={Style.consignee}>收件人：</dt>
                                <dd className={Style.addressName}>{this.state.consigneeAddress.receiveName}</dd>
                            </dl>
                            <dl className={Style.address}>
                                <dt>地址：</dt>
                                <dd className={Style.details}>
                                    <b>{this.state.consigneeAddress.receiveAddress}</b>
                                </dd>
                            </dl>
                            <dl className={Style.address}>
                                <dt>电话：</dt>
                                <dd>{this.state.consigneeAddress.receivePhone}</dd>
                            </dl>
                        </div>
                    </div>
                    }
                    {/**3 下游地址：end */}

                    <div style={{height: '.24rem', backgroundColor: '#f1f1f1'}}></div>

                    {/** 4、 用户地址 :
                     * confirmStatus //按钮的状态 1 未点击  2 说明点击过了，应该隐藏
                     * 上线检只有一个状态 ：confirmStatus=2，不能修改  用户地址
                     */}
                    {this.state.confirmStatus != 3 && this.state.inspectionType.inspectionType == 1 ?
                        <div className='pt20'>
                            {/** 4a 用户地址：未确定 */}
                            <p className='ptb30 plr30 font-30'>年检资料回寄地址：</p>
                            <div className={Style.envelope} onClick={() => {
                                this.context.router.push(`/mailingAddress/${this.props.params.orderId}`);
                                SendCxytjMessage.sendMessage({eventId: 'H5_E_OnlineMaterialandAddresspage_ClickEditAddress'});
                            }}>

                                <div className={Style.name_a}>
                                    <span>{latestAdd.name}</span>
                                    <span>{latestAdd.phone}</span>
                                </div>
                                <p className={Style.address}>
                                    <span>{latestAdd.location}</span>
                                </p>
                                <img className={Style.right_arr} src="./images/right-arr.png" alt=""/>
                            </div>

                        </div>
                        :
                        <div className={Style.box_address}>

                            {/** 4b 用户地址：已确定
                             * 上线检，没有用户地址
                             */}
                            <div className={Style.title_t + '  pt20'}>
                                {this.state.inspectionType.inspectionType == 1 ? '年检办完后，您的资料将回寄到：' : '您的联系方式如下：'}
                            </div>
                            <div className={Style.box_address_phone}>
                                <dl className={Style.address}>
                                    <dt className={Style.consignee}>收件人：</dt>
                                    <dd className={Style.addressName}>{latestAdd.name}</dd>
                                </dl>
                                {this.state.inspectionType.inspectionType == 1 && <dl className={Style.address}>
                                    <dt>地址：</dt>
                                    <dd className={Style.details}>
                                        <b>{latestAdd.location}</b>
                                    </dd>
                                </dl>}
                                <dl className={Style.address}>
                                    <dt>电话：</dt>
                                    <dd>{latestAdd.phone} </dd>
                                </dl>
                            </div>
                            <p className={Style.customerServicePhone}>{this.state.inspectionType.inspectionType == 1 ? '如需更改收件地址，请联系客服' : '如需更改信息，请联系客服'}</p>
                        </div>
                    }

                    {/** 4、 用户地址 :end*/}


                    {this.state.inspectionType.inspectionType == 1 && this.state.confirmStatus &&
                    <Button className={this.state.confirmStatus != 3 ? Style.fixedBtn : Style.btnL} size='large'
                            onClick={e => this.submitConfirmationPostalOwn(this.state.confirmStatus, false, this.paramsType)}>{this.state.confirmStatus != 3 ? (this.state.inspectionType.mailType == 'ems' ? '已备好，可上门收件' : '已确认寄出资料') : '查看订单详情'}</Button>
                    }

                    {this.state.inspectionType.inspectionType == 2 && <Button className={Style.btnL} size='large'
                                                                              onClick={e => this.submitConfirmationPostalOwn(3, true, this.paramsType)}>查看订单详情</Button>
                    }

                    <Service fixed={false} className={Style.bottomService} rightText='联系客服'/>
                    {/*<WhiteSpace size="xl" />*/}
                </div>
            </div>
        )
    }
}


//使用context
SendTheAddress.contextTypes = {
    router: React.PropTypes.object.isRequired
};

//react router跳转时使用了context，此处需要显式声明z
SendTheAddress.contextTypes = {
    router: React.PropTypes.object.isRequired
};

export default connect()(SendTheAddress)
